#include "common.h"
#include "downloadlayout.h"
#include "downloadtask.h"

DownloadTask* DownloadTask::instance = new DownloadTask;
DownloadTask::AutoRelease DownloadTask::_at;

DownloadTask *DownloadTask::getInstance()
{
    return instance;
}

bool DownloadTask::isEmpty()
{
    return list.isEmpty();
}

bool DownloadTask::isDownload()
{
    for(int i = 0; i < list.size(); ++i)
    {
        if(list.at(i)->isDownload == true)
        {
            return true;
        }
    }

    return false;
}

bool DownloadTask::isShareTask()
{
    if(isEmpty())
    {
        return NULL;
    }

    return list.at(0)->isShare;
}

DownloadInfo *DownloadTask::takeTask()
{
    if(isEmpty())
    {
        return nullptr;
    }

    list.at(0)->isDownload = true;
    return list.at(0);
}

void DownloadTask::dealDownloadTask()
{
    for(int i = 0; i != list.size(); ++i)
    {
        if( list.at(i)->isDownload == true) //说明有下载任务
        {
            DownloadInfo* tmp = list.takeAt(i);

            DownloadLayout* downloadLayout = DownloadLayout::getInstance();
            QLayout* layout = downloadLayout->getDownloadLayout();
            layout->removeWidget(tmp->dp);
            delete tmp->dp;

            QFile* file = tmp->file;
            file->close();
            delete file;

            delete tmp;
            return;
        }
    }
}

//追加任务到下载队列
//参数：info：下载文件信息， filePathName：文件保存路径
//成功：0
//失败：
//  -1: 下载的文件是否已经在下载队列中
//  -2: 打开文件失败
int DownloadTask::appendDownloadList(FileInfo *info, QString filePathName, bool isShare)
{
    for(int i = 0; i != list.size(); ++i)
    {
        if(list.at(i)->user == info->user && list.at(i)->filename == info->filename)
        {
            cout << info->filename << "已经在下载队列中";
            return -1;
        }
    }
    QFile* file = new QFile(filePathName);
    if(!file->open(QIODevice::WriteOnly))
    {
        cout << "file open error";
        delete file;
        file = nullptr;
        return -2;
    }

    DownloadInfo* tmp = new DownloadInfo;
    tmp->user = info->user;
    tmp->file = file;
    tmp->filename = info->filename;
    tmp->md5 = info->md5;
    tmp->url = info->url;
    tmp->isDownload = false;
    tmp->isShare = isShare;

    DataProgress* p = new DataProgress;
    p->setFileName(tmp->filename);

    DownloadLayout* downloadLayout = DownloadLayout::getInstance();
    QVBoxLayout* layout = (QVBoxLayout*)downloadLayout->getDownloadLayout();

    tmp->dp = p;
    layout->insertWidget(layout->count()-1, p);

    cout << info->url << "已经添加到下载列表";

    list.append(tmp);
    return 0;
}
